#!/bin/env ruby
# encoding: utf-8

def findNameColumn(name, tableT) 
  j=0
  tableT.thead.trs.each do |row|
    row.cells.each do |cell|
      if cell.text == "#{name}" then break end
      j=j+1
    end
  end
  return j
end

def findManagerId (rowIndex, tableT)  
  i = findNameColumn("Manager", tableT)
  managerName = tableT.tbody[rowIndex][i].text
  j= findNameColumn("Name", tableT)
  k=0
  tableT.tbody.trs.each do |row|
    if row[j].text == managerName then break end
    k=k+1
  end    
  mangerId = tableT.tbody[k].attribute_value('data-employee-id') 
end

def findDepartmentId()
  select_list(id: "js-admin-selector-departments", class: "form-control min-width-selector").selected_options[0].attribute_value('data-department-id')
end

def findRole(rowIndex, tableT)
  i = findNameColumn("Role", tableT)
  return tableT.tbody[rowIndex][i].text
end

def find_managers(departmentId)
  managerList = Array.new
  url = browser.url
  goto 'http://pulse.7bits.it/en/us/admin/employees-list'
  
  selectList = select_list(id: "js-admin-selector-departments", class: "form-control min-width-selector")
  options = selectList.options
  options.each do |opt|
    selectList.select opt.text
    if selectList.attribute_value("data-department-id") == departmentId
      break
    end
  end
  
  #select_list(id: "js-admin-selector-departments", class: "form-control min-width-selector").click  #?
  table(class: "table table-hover table-employees table-striped js-admin-table-for-department").wait_until_present 
  
  tableT = table(class: "table table-hover table-employees table-striped js-admin-table-for-department") 
  i = findNameColumn("Name", tableT)
  j = findNameColumn("Role", tableT)
  tableT.trs.each do |row|    
    if row[j].text == 'Sponsor' or row[j].text == 'Actioner' then         
      managerList << row[i].text           
    end
  end
  goto url
  return managerList
end

def go_employee(num)
  goto 'http://pulse.7bits.it/en/us/admin/employees-list'    
  select_list(id: "js-admin-selector-departments", class: "form-control min-width-selector").select 'cats'      
  tableT = table(class: "table table-hover table-employees table-striped js-admin-table-for-department")
  employeeId = tableT.tbody.trs[num].attribute_value('data-employee-id')            
  goto "http://pulse.7bits.it/en/us/admin/edit-employee?userId=#{employeeId.to_s}"   
end